// pages/appoint/appoint.js
import routerManager from "../../utils/routerManager.js";
import http from "../../utils/http.js";
import util from "../../utils/util2.js";
import Dialog from "/@vant/weapp/dialog/dialog";
const DAY_CN = ["周日","周一","周二","周三","周四","周五","周六"];

Page({
  /**
   * 页面的初始数据
   */
  data: {
    weekActive: 0,
    periods: [],
    price: 0,
    serviceId: null,
    weeks: [],
    chooseTime: null,
    chooseDate: null,
    duration: null,
    serviceName:null,
    showDate: false,
    endTime:null,
    isAndroid:false,
    showtTips:false,
  },
  changeWeek(event) {
    let index = event.currentTarget.dataset.index;
    let chooseDate = this.data.weeks[index].date;
    this.setData({
      weekActive: index,
      chooseDate: chooseDate,
      chooseTime: null
    });
    this.loadPeriods(chooseDate);
  },
  moreDate() {
    this.setData({
      showDate: true
    });
    //routerManager.toMoreDate();
  },
  pay() {
    let that = this;
    if (!this.data.chooseTime || !this.data.chooseDate) {
      Dialog.alert({
        title: "提示",
        message: "请选择日期和时间"
      }).then(() => {
        // on close
      });
      return;
    }
    let orderDateTime = this.data.chooseDate + " " + this.data.chooseTime;
    let service_id = this.data.serviceId;
    Dialog.confirm({
      title: "预约确认",
      message: "预约时间为：" + orderDateTime
    })
      .then(() => {
        http.orderCreate(orderDateTime, service_id, function(res) {
          console.log(res);
          if (res.error == 0) {
            let orderId = res.data.id;
            wx.getSystemInfo({
              success:function(systemInfo){
                let payType = 0;
                console.log("systemInfo.platform ",systemInfo);
                if(systemInfo.platform == "devtools"){
                  payType = 2;
                } else if(systemInfo.platform == "ios"){
                  payType = 2;
                } else if(systemInfo.platform == "android"){
                  payType = 1;
                }
                http.orderPay(orderId, payType, function(_res) {
                  console.log("_res", _res);
                  if (_res.error == 0) {
                    routerManager.redirectToOrders();
                  } else {
                    if(payType == 2){
                      that.setData({
                        showtTips:true,
                      })
                    } else {
                      wx.wx.showToast({
                        title: res.message,
                        icon: ''
                      })
                    }
                   
                  }
                });
              }
            })
          }
        });
        // on confirm
      })
      .catch(() => {
        // on cancel
      });
    // http.orderCreate();
  },
  onClose(){
    this.setData({
      showtTips:false
    })
  },
  handleContact: function(e) {
    console.log(e.detail.path);
    console.log(e.detail.query);
  },
  onChooseTime(event) {
    let time = event.currentTarget.dataset.time;
    let date = new Date();
    date.setHours(time.split(":")[0]);
    date.setMinutes(time.split(":")[1]);
    let endDate = new Date(date.getTime() + (parseInt(this.data.duration) * 60 * 1000));
    let endTime;
    if (endDate.getMinutes() < 10) {
      endTime = endDate.getHours() + ":0" + endDate.getMinutes();
    } else {
      endTime = endDate.getHours() + ":" + endDate.getMinutes();
    }
   
    this.setData({
      chooseTime: time,
      endTime:endTime
    });
  },
  loadPeriods(date) {
    let that = this;
    let service_id = this.data.serviceId;
    http.reservedPeriods(date, service_id, function(res) {
      that.setData({
        periods: res.data.periods
      });
    });
  },
  initWeeks(today) {
    let oneDayLong = 24 * 60 * 60 * 1000;
    let weeks = [];
    //let today = new Date();
    let todayCN = "";
    if(util.formatTime(today) === util.formatTime(new Date())){
      todayCN = "今日";
    } else {
      todayCN = DAY_CN[today.getDay()];
    }
    weeks.push({
      week: todayCN,
      date: util.formatTime(today),
      weekActive: 0
    });
    for (let i = 0; i < 3; i++) {
      today.setTime(today.getTime() + oneDayLong);
      let dayCN = "";
      if(today.getDay() == 0){

      }
      weeks.push({
        week: DAY_CN[today.getDay()],
        date: util.formatTime(today),
        weekActive: i + 1
      });
    }
    let chooseDate = weeks[0].date;
    console.log("init chooseDate",chooseDate)
    this.setData({
      weeks: weeks,
      chooseDate: chooseDate
    });
  },
  selectDate(event) {
    console.log("date", event.detail);
    this.setData({
      showDate: false,
      chooseTime: null
    });
    if(event.detail.select){
      this.setData({
        chooseDate:event.detail.select
      })
    }
    this.initWeeks(event.detail.date);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("options.serviceId", options);
    let that = this;
    let date = util.formatTime(new Date());
    that.setData({
      serviceId: options.serviceId,
      price: options.price,
      duration: options.duration,
      serviceName:options.serviceName
    });
    wx.getSystemInfo({
      success:function(systemInfo){
        let price = parseFloat(that.data.price);
        if(systemInfo.platform == "devtools" || systemInfo.platform == "android"){
          price = (price + (price * 0.01));
          that.setData({
            price:price.toFixed(2)
          })
        }
      }
    })
    this.loadPeriods(date);
    this.initWeeks(new Date());
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
